import { Toast } from 'antd-mobile';
import { Config } from '../config';
import { history } from 'umi';
import { getToken, setToken } from './authority';
import axios from 'axios';
import qs from 'qs';

export default function request(url, options) {
  return new Promise((resolve, reject) => {
    let { method, body, arrayFormat = 'indices' } = options;
    // 添加url前缀
    if (!url.indexOf('https://') > -1 || !url.indexOf('http://') > -1) {
      url = Config.SERVER_HOME + (url.indexOf('/') === 0 ? url.substr(1) : url);
    }
    let option = {
      method,
      url,
      header: {
        Accept: 'application/json',
        Pragma: 'no-cache',
        'Cache-Control': 'no-cache',
        Expires: 0,
        'Content-Type': 'application/json; charset=utf-8',
        // 'Authorization':"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySUQiOjEsImlhdCI6MTYwMTI4NTYyN30.IO_C69dL7xJQ956NNDhy-W-ICTqFr5SFzL97qr_qFi4"
      },
      paramsSerializer: function (params) {
        return qs.stringify(params, { arrayFormat, allowDots: true });
      },
    };
    // TODO 添加token
    let token = getToken();
    if (token) {
      option.headers = option.headers || {};
      option.headers.Authorization = `Bearer ${token}`;
      // option.headers = { ...option.headers, 'X-API-KEY': 123456 };
      // delete option.headers['X-API-KEY'];
    } else {
      // option.headers =  { ...option.headers, 'X-API-KEY': 123456 };
    }
    option.headers = { ...option.headers, 'X-API-KEY': 123456 };

    const testUrl = [
      '/business-opportunity',
      '/business-opportunities',
      '/business-opportunity-meet-apply',
    ];
    if (testUrl.some((url) => option.url.indexOf(url) > -1)) {
      if (process.env.NODE_ENV == 'development') {
        option.url = option.url.replace(
          'https://api.e-chinacycle.com',
          'http://47.102.126.217:8930',
        );
      }
      option.headers && delete option.headers.Authorization;
    }

    // 参数赋值
    switch (method) {
      case 'GET':
      case 'DELETE':
        option.params = body || {};
        break;
      case 'POST':
      case 'PATCH':
      case 'PUT':
        option.data = body || {};
        break;
      default:
        break;
    }

    axios(option)
      .then((response) => {
        resolve(response.data);
      })
      .catch((error) => {
        Toast.hide();
        if (error.response) {
          let { status, data } = error.response;
          // console.log(status, 'statuslogin')
          if (status === 400) {
            let { message } = data;
            Toast.info(message, 2);
          }
          if (status === 401) {
            Toast.info('登录过期重新登录！');
          }

          if (status === 500) {
            resolve({
              error: {
                status: 500,
                message: (data.error && data.error.message) || data.message,
              },
            });
          }
        } else if (error.request) {
          throw error;
        } else {
          throw error;
        }
      });
  });
}

export function requestGet(url, body) {
  return request(url, { method: 'GET', body });
}
export function requestDelete(url, body) {
  return request(url, { method: 'DELETE', body });
}
export function requestPost(url, body) {
  return request(url, { method: 'POST', body });
}
export function requestPatch(url, body) {
  return request(url, { method: 'PATCH', body });
}
export function requestPut(url, body) {
  return request(url, { method: 'PUT', body });
}
